package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;


    //处理新增请求
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission) {
        if (permission.getId() != null) {//修改
            permissionService.update(permission);
        } else { //新增
            permissionService.save(permission);
        }
        return "redirect:/permission/list.do";

    }

    //处理去新增请求
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //若传 id 值,表示是去修改,那就要去查询被修改的部门对象,存在模型中
        if (id != null) { // 表示去修改
            Permission permission = permissionService.get(id);
            model.addAttribute("permission", permission);
        }
        // /WEB-INF/views/permission/input.jsp
        return "permission/input";
    }

    //处理删除部门请求
    @RequestMapping("/delete")
    @ResponseBody
    private JsonResult delete(Long id) {
        //传了id值就删除对应的权限数据
        try {
            if (id != null) {
                permissionService.delete(id);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }


    // 处理查询所有部门请求
    @RequestMapping("/list")
    public String list(Model model,QueryObject qo) {
        /*PageResult<Permission> pageResult = permissionService.query(qo);*/
        model.addAttribute("pageInfo", permissionService.query(qo));
        return "permission/list"; // 找视图 /WEB-INF/views/permission/list.jsp
    }


    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        System.out.println(1);
        try {
            permissionService.reload();
            System.out.println(2);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(3);
            return new JsonResult(false,"加载失败,请联系管理员");
        }
    }
}